import 'package:flutter/material.dart';
import 'package:flutter04/res/listData.dart';

void main(){
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title:const Text("Grid View")
        ),
        // body:const MyHomePageByFor(),
        body:const MyHomePage(),

      ),
    );
  }
}
//for/map遍历赋值方式
class MyHomePageByFor extends StatelessWidget {
  const MyHomePageByFor({super.key});
  List<Widget> _initGridViewData(){
   //第一种for循环方式
    // List<Widget> tempList = [];
    //   for(int i = 0;i<20;i++){
    //     tempList.add( Container(
    //       alignment: Alignment.center,
    //       decoration:const BoxDecoration(
    //         color: Colors.red,
    //       ),
    //       child: Text("网格$i"),
    //     ));
    //   }
    // return tempList;
    //Map方式
    var tempList = listData.map((value){
      return Container(
        alignment: Alignment.center,
        decoration:const BoxDecoration(
          color: Colors.red,
        ),
        child: Text("${value["title"]}",
          textAlign: TextAlign.center,
          style:const TextStyle(
              color: Colors.white,
              fontSize: 18
          ),),
      );

    });
    return tempList.toList();
  }
  @override
  Widget build(BuildContext context) {

    return GridView.count(crossAxisCount: 3,
    padding:const EdgeInsets.all(10),
    crossAxisSpacing: 10,
    mainAxisSpacing: 10,
    children:  _initGridViewData(),);
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  Widget _initGridViewItemBuilder(context,index){
      return Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black12)
        ),
        child: Column(
          children: [
            Image.network(listData[index]["imageUrl"]),
            Text(
              listData[index]["title"],
              textAlign: TextAlign.center,
              style:const TextStyle(
                fontSize: 16,
                color: Colors.black54
              ),
            )
          ],
        ),
      );
  }
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate:const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount:3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio:0.8,
      ),
      padding:const EdgeInsets.all(10),
      itemCount: listData.length,
      itemBuilder: _initGridViewItemBuilder,
    );
  }
}

